package conceptualization;

import java.util.*;
import java.io.*;

public class Conceptualizer {
	private Parser parser;
	
	public Conceptualizer(Parser parser) {
		this.parser = parser;
	}
	
	/********
	 * Conceptualize instances in query log
	 * @param qIndex query index
	 * @param qryLog query
	 * @return conceptualization result, null if cannot conceptualized. 
	 */
	public ProResult conceptualize(int qIndex, String qryLog) {
		String[] log = qryLog.split("\\t");
		if (log.length != 4) return null; // wrong lines, just abandon them, and return null
		ProResult ans = new ProResult(qIndex, log[0], Integer.parseInt(log[1]), log[2], log[3]);
		
		String[] terms = log[0].split(" ");
		int max = terms.length, length = terms.length;
		ArrayList<String> tempResult = new ArrayList<String>();
		while (max != 0) {
			for (int i = 0; i + max <= length; i++) {
				String test = rebuild(terms, i, i+max);
				if (parser.containInstance(test) && parser.canConceptualize(parser.instanceIndex(test))) {
					test += "\t" + parser.instanceTypical(parser.instanceIndex(test));
					terms[i] = test;
					for (int j = i+max; j < length; j++) {
						terms[j-max+1] = terms[j];
					}
					length = length - max + 1;
				}
			}
			max--;
		}
		for (int i = 0; i < length; i++) {
			ans.addPartition(terms[i]);
		}
		return ans;
	}
	
	private String rebuild(String[] terms, int start, int end) {
		String ans = "";
		for (int i = start; i < end; i++) {
			if (i == start) ans += terms[i];
			else ans += " " + terms[i];
		}
		return ans;
	}
}
